import React, { ReactNode, useReducer, useMemo, Dispatch, createContext } from 'react';

export enum ActionType {
    ADD_COUNT = 'ADD_COUNT',
    ADD_NUM = 'ADD_NUM',
    SET_LOADING = 'SET_LOADING',
}

type State = {
    count: number;
    num: number;
    loading: boolean;
};

type AddCountAction = {
    type: ActionType.ADD_COUNT;
};

type AddNumAction = {
    type: ActionType.ADD_NUM;
};

type SetLoadingAction = {
    type: ActionType.SET_LOADING;
    loading: boolean;
};

const initialState: State = { count: 0, num: 0, loading: false };

export const MyContext = createContext<{
    state: State;
    dispatch: Dispatch<AddCountAction | AddNumAction | SetLoadingAction>;
}>({
    state: initialState,
    dispatch: () => {},
});

function reducer(state: State, action: AddCountAction | AddNumAction | SetLoadingAction) {
    switch (action.type) {
        case ActionType.ADD_COUNT: {
            return {
                ...state,
                count: state.count + 1,
            };
        }
        case ActionType.ADD_NUM: {
            return {
                ...state,
                num: state.num + 1,
            };
        }
        case ActionType.SET_LOADING: {
            return {
                ...state,
                loading: action.loading,
            };
        }
        default:
            return state;
    }
}

export function MyProvider({ children }: { children: ReactNode }) {
    const [state, dispatch] = useReducer(reducer, initialState);
    const value = useMemo(() => {
        return {
            state,
            dispatch,
        };
    }, [state, dispatch]);
    return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
}
